App.controller("taskListCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	var params = JSON.parse($stateParams.params);
	console.log("路由参数：",params);
	
	$scope.search = {};		//搜索参数
	$scope.form = {};		//表单参数
	$scope.submit_show = true;		//提交（显示）
	
	var guiderTree = null		//导购树;
	
	var alertModel = {};	//alert模态框
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}

	
	//表格对象
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/selectUserManagerActivityTaskList",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field!="createTime"){
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									activity_id: params.activityId,		//活动Id
									
									state: $("#taskState").data("kendoDropDownList").value(),
									create_time_start: $("#startTime").val(),
									create_time_end: $("#endTime").val(),
									
									sort:sort
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						return d.data;
					},
					total : function(d) {
						return d.total; //总条数
					}
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },  
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "single"     //排序模式：single，multiple
			  },
			editable: false,  //true：单个编辑；popup：弹出新页面编辑
			dataBound: function () {   //序号
		        var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
		    },
			columns : [
					{    
						title : "序号",
						field : "id", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' value='#: id #' />"+"<span class='row-number subTitle'></span>"
					},
					{
						field : "create_time",         
						title : "创建日期",     
						width : "100px"
					},
					{
						field : "task_starttime",         
						title : "任务起止日期",     
						width : "200px",
						template: function(e){
					    	return e.task_starttime+"-"+e.task_endtime;
					    }
					},
					{
						field : "shop_num",         
						title : "参与专卖店数量",     
						width : "100px"
					},
					{
						field : "order_num",         
						title : "目标成单数",     
						width : "100px"
					},
					{
						field : "sign_rate",         
						title : "目标签单率",     
						width : "100px",
						template: function(e){
					    	return e.sign_rate+"%";
					    }
					},
					{
						field : "state",         
						title : "任务状态",     
						width : "100px",
						values: [
						         { text: "未开始", value: 1 },
						         { text: "进行中", value: 2 },
						         { text: "已结束", value: 3 },
						         { text: "已暂停", value: 4 }
				        ],
					},
					{
						field : "",         
						title : "操作",     
						width : "100px",
						template: function(e){
					    	var html = '';
					    	
					    	if(e.state==1){
					    		html += '<div class="operation" ng-click="lookOrEdit('+e.id+',1)">编辑</div>';
					    	}else{
					    		html += '<div class="operation" ng-click="lookOrEdit('+e.id+',2)">查看详情</div>';
					    	}

					    	return html;
					    },
					}
			]
	};
	
	//查询
	$scope.search = function(){
		$scope.grid.dataSource.page(1);
	}
	
	//查看或编辑
	$scope.lookOrEdit = function(id,type){	
		
		$http({
			   url:	path+'/server/selectUserManagerActivityTaskEcho/'+id,
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){
				var taskInfo = data.result;
				
				$scope.form.activityTaskId = id;
				$scope.form.task_starttime = taskInfo.task_starttime;
				$scope.form.task_endtime = taskInfo.task_endtime;
				guiderTree = publicService.initZtree("ztree",taskInfo.user_userManager_tree); 
				$scope.form.activity_num = taskInfo.activity_num;
				$scope.form.sign_rate = taskInfo.sign_rate;
				
				$scope.activityTaskWindow.center().open();   //打开弹框
				
				if(type==1){	//编辑
					$scope.submit_show = true;
					$(".windowForm").find("input").removeAttr("disabled");
				}else{
					$scope.submit_show = false;
					$(".windowForm").find("input").attr("disabled","disabled");
				}
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//任务编辑
	$scope.taskUpdateSubmit = function(){
		var shopIdArr = [];		//专卖店
		var guiderIdArr = [];	//导购
		
		var checkedNodes = guiderTree.ztree.getCheckedNodes(true);
    	$.each(checkedNodes, function(index, OneObj){
    		if(!OneObj.parent_id || OneObj.parent_id==0){
    			shopIdArr.push(OneObj.id);
    		}else{
    			guiderIdArr.push(OneObj.id);
    		}
		});
		
		$scope.form.user_userManager_tree = {	//专卖店，导购
				shop_id: shopIdArr,
				ids: guiderIdArr
		};	
		
		if(guiderIdArr.length==0){
			$scope.alertMessage("请选择导购人员！");
			return;
		}
		if(!$scope.form.activity_num){
			$scope.alertMessage("请输入活动成单数！");
			return;
		}else{
			if(!publicService.checkIsUpNumber($scope.form.activity_num)){
				$scope.alertMessage("活动成单数请输入正确的数值！");
				return;
			}
		}
		if(!$scope.form.sign_rate){
			$scope.alertMessage("请输入签到率！");
			return;
		}else{
			if($scope.form.sign_rate<0 || $scope.form.sign_rate>100){
				$scope.alertMessage("签到率区间为[0,100]！");
				return;
			}
		}
		
		$http({
			   url:  path+'/server/updateUserManagerActivityTask',
			   method: 'POST',   
			   data: angular.toJson($scope.form)
		}).success(function(data){
			if(data.code==0){
				$scope.activityTaskWindow.close();
				$scope.alertMessage("成功！");
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			console.warn(data);   
		})
	}
	
	
	publicService.initTaskState("taskState");//初始化【任务状态】
	publicService.initDateTime("startTime");	 //创建时间（始）
	publicService.initDateTime("endTime");		 //创建时间（止）

	
	
	
	
	
});